package com.jinqing.wuchuang.config;


import com.jinqing.wuchuang.RedisMapper.RedisAuthUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 这里也需要修改，抛出的异常不能直接时exception
 */
public class ValidateCodeFilter extends OncePerRequestFilter {
    @Autowired
    private RedisAuthUserMapper redisAuthUserMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // authentication/form是认证时的请求接口，验证码校验只需要匹配这个接口即可
        if ("/authentication/form".equals(request.getRequestURI()) &&
                "post".equals(request.getMethod())) {
            try {
                validate(new ServletWebRequest(request));
            } catch (Exception e) {
                // 校验失败时，让失败的处理器去处理authenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        // 无异常即校验成功，放行。
        filterChain.doFilter(request, response);

    }

    private void validate(ServletWebRequest request) throws Exception {
        //从redis取出验证码
        String captcha = redisAuthUserMapper.getValueByCode(request.getParameter("code"));
        // 从客户端接收到的验证码
        String captchaParam = request.getParameter("captcha");

        if (captchaParam.isEmpty()) {
            throw new Exception("验证码不能为空");
        }

        if (captcha == null) {
            throw new Exception("验证码不存在");
        }

        if (!captcha.equals(captchaParam)) {
            throw new Exception("验证码不匹配");
        }
    }
}